import { allOf, IMatcher } from "db://delta/ecs/ecs";
import { ECSComblockSystem } from "db://delta/ecs/ecs_system";
import { RenderCompent } from "../compents/render_compent";
import { ECSEntity } from "db://delta/ecs/ecs_entity";
import { find, instantiate, Prefab } from "cc";
import { resolader } from "db://delta/loader/Resloader";
import { PositionCompent } from "../compents/position_compent";

export class RenderSystem extends ECSComblockSystem {
  constructor() {
    super();
  }

  filter(): IMatcher {
    return allOf(RenderCompent);
  }
  init() {

  }

  entityEnter(entity: ECSEntity) {
    console.log('entityEnter', entity);
    
  }

  entityRemove(entity: ECSEntity) {
    console.log('entityRemove', entity);

  }

  firstUpdate(entity: ECSEntity) {
    // console.log('render system first update', entity);
    const comp = entity.get(RenderCompent);
    resolader.loadAsync(comp.bundleName, comp.resPrefabPath, Prefab).then((prefab: Prefab) => {
      const canvas = find("Canvas");
      const monsternode = instantiate(prefab);
      monsternode.parent = canvas;
      const poscomp = entity.get(PositionCompent);
      if (poscomp) {
        monsternode.setPosition(poscomp.pos.x, poscomp.pos.y, 0);
      }
      comp.renderNode = monsternode;
    });
  }

  update(entity: ECSEntity) {

    const rendercomp = entity.get(RenderCompent);
    if (rendercomp?.renderNode) {
        const poscomp = entity.get(PositionCompent);
      if (poscomp) {
        rendercomp.renderNode.setPosition(poscomp.pos.x, poscomp.pos.y, 0);
      }
    }
  }


}

